import {Tree, Row, Col, Input, Modal, Table, Tabs, Pagination, Select, Menu, Button, Dropdown, Icon, Form, message, Checkbox, Spin} from 'antd';
// import Tree from '../../../_antd1.11.2/Tree';
// import Row from '../../../_antd1.11.2/Row';
// import Col from '../../../_antd1.11.2/Col';
// import Input from '../../../_antd1.11.2/Input';
// import Modal from '../../../_antd1.11.2/Modal';
// import Table from '../../../_antd1.11.2/Table';
// import Tabs from '../../../_antd1.11.2/Tabs';
// import Pagination from '../../../_antd1.11.2/pagination';
import isEqual from 'lodash/isEqual';

const TabPane = Tabs.TabPane;
const TreeNode = Tree.TreeNode;
// import Select from '../../../_antd1.11.2/Select';
const Option = Select.Option;
// import Menu from '../../../_antd1.11.2/menu';
const SubMenu = Menu.SubMenu;
const MenuItemGroup = Menu.ItemGroup;
// import Button from '../../../_antd1.11.2/Button';
// import Dropdown from '../../../_antd1.11.2/Dropdown';
// import Icon from '../../../_antd1.11.2/Icon';
// import Form from '../../../_antd1.11.2/Form'
const FormItem = Form.Item;
// import message from '../../../_antd1.11.2/message'
import cloneDeep from 'lodash/cloneDeep';
import forEach from 'lodash/forEach';
import isEmpty from 'lodash/isEmpty'
// import Checkbox from '../../../_antd1.11.2/Checkbox'
const CheckboxGroup = Checkbox.Group;

import WeaInputSearch from '../../wea-input-search';
import WeaTree from '../wea-tree';
import WeaSearchBrowserBox from '../wea-search-browser-box';
import WeaDropMenu from '../wea-drop-menu';
import WeaAssociativeSearchMult from '../wea-associative-search-mult'
import WeaDepInput from '../../wea-dep-input';
import WeaComInput from '../../wea-com-input';
import WeaNewScroll from '../../wea-new-scroll';
import WeaInput from '../../wea-input';
import WeaSelect from '../../wea-select';
import WeaInputRoleNew from '../wea-input4-role-new';
import WeaWorkflowTableHrMult from '../wea-workflow-table-hr-mult';
import WeaTreeHr from '../wea-tree-hr';
import Operation from './operation';
import WeaTransferRight from '../wea-transfer-right';
import WeaTreeHrMult from '../wea-tree-hr-mult';
import WeaTools from '../../wea-tools';
import WeaHrmList from '../wea-hrm-list';
import uniq from 'lodash/uniq'
// import Spin from '../../../_antd1.11.2/Spin';
import uniqBy from 'lodash/uniqBy'
import debounce from 'lodash/debounce'


const initialState = {
    activeKey:"1",
    searched:false,
    showSearchAd:false,
    url: '/api/ec/api/hrm/newly', // 最近
    hasPagination: true,
    count: 0,
    visible: false,
    currentPage: 1,
    inputValue: '',
    searchPara: {},
    browserConditions:[],
    isAccount: false,
    checkStrictly: false,
    leftListSelectedKeys: [],
    leftListSelectedData: [],
    showAllbranch: false,
    showList: true,
    listDatas: [],
    loading: true,
}
let that;

class main extends React.Component {
    static Operation = Operation;
    static defaultProps = {
        mult:true,
        topPrefix: 'wea',
        isShowGroup: false,
    }
    constructor(props) {
        super(props);
        this.state = {
            visible: null,
            showDrop:false,
            activeKey:"1",
            virtualDatas:[],
            companysDefault:'',
            companyId: null,
            initialShowSearchAd:false,
            showSearchAd:false,
            grouptreeData:null,
            rsctreeData:null,
            searched:false,  // 高级搜索的状态
            isClearData: false,
            rightCheckedKeys: [], //右侧选择的keys
            rightDatas:[],  // 右侧展示的数据
            leftListSelectedKeys:[], // 左侧table选择的keys
            leftListSelectedData: [], // 左侧table选择的数据
            leftTreeCheckedKeys:[], // 左侧tree选择的keys
            leftTreeCheckedData:[], // 左侧tree选择的数据
            selectedData: {}, // 搜索按钮选中的数据
            searchKeys:[], // 搜索按钮选择的keys
            leftGroupCheckedKeys: [], //左侧group 选择的keys
            leftGroupCheckedData: [],
            listDatas: [],
            currentPage: 1,
            pageSize: 20,
            hasPagination: true,
            count: 0,
            url: '/api/ec/api/hrm/newly',
            inputValue: '',
            searchPara: {},
            hiddenIds:'',
            browserConditions: [],
            quickSearch: '',
            checkStrictly: false, // 是否联动子节点
            isAccount: false,  // 有无账号
            showAllbranch: false,
            loading: true,
        }
        that = this;
    }
    componentDidMount() {
        // 默认显示数据
        if (!isEmpty(this.props.appendDatas)) {
            this.appendSearchValues(this.props.appendDatas, true);
        }
        if (!isEmpty(this.props.replaceDatas)) {
            this.replaceSearchValues(this.props.replaceDatas);
        }
    }
    componentWillReceiveProps(nextProps){
        if (this.props.value !== nextProps.value && isEmpty(nextProps.value)) {
            this.setState({isClearData: !this.state.isClearData});
            this.handleClear();
        }
        if (this.props.appendDatas !== nextProps.appendDatas && nextProps.appendDatas && nextProps.appendDatas.length > 0) {
            this.appendSearchValues(nextProps.appendDatas, true);
        }
        if (!isEqual(this.props.replaceDatas, nextProps.replaceDatas)) {
            this.replaceSearchValues(nextProps.replaceDatas || []);
        }
    }
    shouldComponentUpdate(nextProps, nextState) {
        return this.props.value !== nextProps.value
            || this.props.appendDatas !== nextProps.appendDatas
            || this.props.replaceDatas !== nextProps.replaceDatas
            || this.props.form !== nextProps.form
            || this.state.visible !== nextState.visible
            || this.state.activeKey !== nextState.activeKey
            || this.state.virtualDatas !== nextState.virtualDatas
            || this.state.companysDefault !== nextState.companysDefault
            || this.state.companyId !== nextState.companyId
            || this.state.initialShowSearchAd !== nextState.initialShowSearchAd
            || this.state.showSearchAd !== nextState.showSearchAd
            || this.state.grouptreeData !== nextState.grouptreeData
            || this.state.rsctreeData !== nextState.rsctreeData
            || this.state.searched !== nextState.searched
            || this.state.isClearData !== nextState.isClearData
            || this.state.rightCheckedKeys !== nextState.rightCheckedKeys
            || this.state.rightDatas !== nextState.rightDatas
            || this.state.leftListSelectedKeys !== nextState.leftListSelectedKeys
            || this.state.leftListSelectedData !== nextState.leftListSelectedData
            || this.state.leftTreeCheckedKeys !== nextState.leftTreeCheckedKeys
            || this.state.leftTreeCheckedData !== nextState.leftTreeCheckedData
            || this.state.selectedData !== nextState.selectedData
            || this.state.searchKeys !== nextState.searchKeys
            || this.state.leftGroupCheckedKeys !== nextState.leftGroupCheckedKeys
            || this.state.leftGroupCheckedData !== nextState.leftGroupCheckedData
            || this.state.showDrop !== nextState.showDrop
            || this.state.listDatas !== nextState.listDatas
            || this.state.currentPage !== nextState.currentPage
            || this.state.hasPagination !== nextState.hasPagination
            || this.state.inputValue !== nextState.inputValue
            || this.state.browserConditions !== nextState.browserConditions
            || this.state.isAccount !== nextState.isAccount
            || this.state.checkStrictly !== nextState.checkStrictly
            || this.state.showAllbranch !== nextState.showAllbranch
            || this.state.count !== nextState.count;
    }
    callApi(){
        const {virtualUrl} = this.props;
        WeaTools.callApi(virtualUrl,"GET").then((data)=>{//,{isaccount:isaccount,min:min,max:max}
            let companysDefault = data.datas.map(item => {if (item.id==0) return item.virtualtype})
            this.setState({
                companysDefault: companysDefault,//获取行政组织
                virtualDatas: data.datas,
            });
            this.companysDefault = companysDefault;
            this.companysDefaultId = 0;
        });
        this.getResourceTree();
        this.getGrouptree();
    }
    setLoading(bool) {
        this.setState({loading: bool});
    }
    getResourceTree(companyId = 0, isAccount = true) {
        const {resourcetree} = this.props;
        let params = {};
        if (companyId < 0) params.virtualtype = companyId;
        if (isAccount) params['isNoAccount'] = 1;
        this.setLoading(true);
        WeaTools.callApi(resourcetree, 'GET', params).then((datas)=>{//按照组织结构
            this.setState({rsctreeData:datas, loading: false});
        });
    }
    getGrouptree(isAccount = true) {
        const {grouptree} = this.props;
        let params = {};
        if (isAccount) params['isNoAccount'] = 1;
        this.setLoading(true);
        WeaTools.callApi(grouptree, 'GET', params).then((datas)=>{//常用组
            this.setState({grouptreeData: datas, loading: false});
        });
    }
    onBranchBtnClick() {
        const {showAllbranch, isAccount} = this.state;
        let url = '/api/ec/api/hrm/branch';
        this.getLists(url, 1, true, this.defaultConditionParams, null, isAccount, !showAllbranch);
        this.setState({showAllbranch: !showAllbranch});
    }
    onAccountBtnClick() {
        const {searched, isAccount, activeKey, showAllbranch} = this.state;
        let url;
        let params = this.defaultConditionParams;
        if (searched) {
            url = '/api/ec/api/hrm/search',
            params = this.state.searchPara;
        }
        else if (activeKey === '1') {
        } else if (activeKey === '2') {
            url = '/api/ec/api/hrm/underling'  //同部门
        } else if (activeKey === '3') {
            url = '/api/ec/api/hrm/branch'  //我的下属
        } else if (activeKey === '4') { // 组织结构
            const {companyId} = this.state;
            this.getResourceTree(companyId, !isAccount);
        } else if (activeKey === '5') {
            this.getGrouptree(!isAccount);
        }
        if (searched || activeKey === '2' || activeKey === '3') {
            this.getLists(url, 1, true, params, null, !isAccount, showAllbranch);
        }
        this.setState({isAccount: !isAccount, currentPage: 1});
    }
    getLists(url, currentPage, hasPagination, searchPara = {}, companyId, isAccount = true, showAllbranch = false, activeKey) {
        this.setLoading(true);
        let params = {...searchPara};
        const {pageSize} = this.state;
        url = url || this.state.url;
        currentPage = currentPage || this.state.currentPage;
        hasPagination = hasPagination || this.state.hasPagination;
        if (companyId === undefined || companyId === null) {
            companyId = this.state.companyId;
        }
        if (hasPagination) {
            params['min'] = (currentPage - 1) * pageSize + 1;
            params['max'] = currentPage * pageSize;
        }
        if (companyId) params['virtualtype'] = companyId;
        if (isAccount) params['isNoAccount'] = 1;
        activeKey = activeKey || this.state.activeKey;
        if (showAllbranch && activeKey === '3') params['alllevel'] = 1;
        WeaTools.callApi(url,'GET', params).then((data)=> {
            data.datas.forEach((item)=> {
                item.icon = item.messagerurl;
                item.nodeid = `resource_${item.id}x`;
                item.type = 'resource'
            })
            this.setState({listDatas: data.datas, count: data.count, loading: false});
        })
    }
    onTabsChange(activeKey) {
        let url, companyId, hasPagination = true;
        const {resetFields, setFieldsValue} = this.props.form;
        const {isAccount, showAllbranch} = this.state;
        this.setState({browserConditions: []});
        resetFields();
        if (activeKey === '1') {
            url = '/api/ec/api/hrm/newly' // 最近
            companyId = null
        } else if (activeKey === '2') {
            url = '/api/ec/api/hrm/underling'  //同部门
            companyId = this.companysDefaultId
        } else if (activeKey === '3') {
            url = '/api/ec/api/hrm/branch'  //我的下属
            companyId = this.companysDefaultId
        } else if (activeKey === '4') { // 组织结构
            companyId = this.companysDefaultId
            this.getResourceTree(companyId, isAccount);
            hasPagination = false
        } else {
            companyId = null
            hasPagination = false
        }
        const quickSearch = this.state.quickSearch || 'name';
        this.setState({
            hasPagination,
            url,
            activeKey,
            companyId,
            count: 0,
            currentPage: 1,
            inputValue: this.defaultConditionParams[quickSearch] || '',
            showSearchAd: false,
            searched: false,
            companysDefault: this.companysDefault,
            browserConditions: this.browserConditionsBk,
            searchPara: this.defaultConditionParams,
        });
        if (activeKey === '1' || activeKey === '2' || activeKey === '3') {
            this.getLists(url, 1, true, this.defaultConditionParams, 0, isAccount, showAllbranch, activeKey);
        }
        this.refs.weaSrcoll && this.refs.weaSrcoll.scrollerToTop();
    }
    onPageChange(page) {
        this.getLists('', page, true, this.state.searchPara, '', this.state.isAccount, this.state.showAllbranch);
        this.setState({currentPage: page});
        this.refs.weaSrcoll && this.refs.weaSrcoll.scrollerToTop();
    }
    onSearchChange(v){//按照人员姓名搜索
        const quickSearch = this.state.quickSearch || 'name';
        const {setFieldsValue,validateFields} = this.props.form;
        let params = {};
        validateFields((errors, object) => {
            if (!!errors) {
                message.error('Errors in form!!!');
                return;
            }
            forEach(object, (value, key) => {
                if (value) params[key] = value;
            })
        });
        params[quickSearch] = v;
        const url = '/api/ec/api/hrm/search';
        this.getLists(url, 1, true, params, 0, this.state.isAccount); // 搜索获取数据
        setFieldsValue(params); // 高级搜索数据联动
        this.setState({
            searched: true,
            hasPagination: true,
            inputValue: v,
            url,
            showSearchAd: false,
            activeKey: '',
            searchPara: params
        });
        this.refs.weaSrcoll && this.refs.weaSrcoll.scrollerToTop();
    }
    goSearch=(e)=>{
        e.preventDefault();
        this.refs.weaSrcoll && this.refs.weaSrcoll.scrollerToTop();
        const quickSearch = this.state.quickSearch || 'name';
        const {validateFields} = this.props.form;
        let params = {};
        validateFields((errors, object) => {
            if (!!errors) {
                message.error('Errors in form!!!');
                return;
            }
            forEach(object, (value, key) => {
                if (value) params[key] = value;
            })
        });
        const url = '/api/ec/api/hrm/search';
        // console.log('params',params);
        this.getLists(url, 1, true, params, 0, this.state.isAccount); // 搜索获取数据
        this.setState({
            hasPagination: true,
            searchPara: params,
            showSearchAd:false,
            searched:true,
            inputValue: params[quickSearch] || '',
            activeKey: '',
            url
        });
    }
    showModal() {
        this.setState({visible: true});
    }
    onSelect(e){
        const {resourcetree} = this.props;
        const {activeKey, virtualDatas} = this.state;
        let _this = this;
        virtualDatas.forEach((item)=>{
            if(e.key == item.id){
                _this.setState({
                    companysDefault: item.virtualtype,
                    companyId: e.key
                });
                if (activeKey === '4') {
                    this.getResourceTree(e.key);
                } else {
                    this.getLists(null, 1, true, {}, e.key);
                }
            }
        })
    }

    setShowSearchAd(bool){
        const {showSearchAd}=this.state;
        this.setState({showSearchAd:bool, initialShowSearchAd:true})
    }
    onBrowerClick =(keys, selectedObj)=>{
        const {resetFields} = this.props.form;
        resetFields(); // 重置高级搜索
        const {conditionURL} = this.props;
        WeaTools.callApi(conditionURL,'GET').then(data=>{
            let quickSearch;
            if (!isEmpty(data.conditions)) {
                data.conditions.forEach((item)=> {
                    if (item.isQuickSearch) {
                        quickSearch = item.domkey[0];
                    }
                })
            }
            const params = WeaTools.getParamsByConditions(data.conditions);
            let url = null, activeKey = '1', searched = false;
            if (!isEmpty(params)) {
                // 初始条件更新在form中
                const {setFieldsValue} = this.props.form;
                setFieldsValue(params);
                url = '/api/ec/api/hrm/search';
                activeKey = '';
                searched = true;
            }
            this.setState({browserConditions: data.conditions, quickSearch,
                inputValue: params[quickSearch] || '',
                searchPara: params, url, activeKey, searched});
            this.browserConditionsBk = data.conditions;
            this.defaultConditionParams = {...params};
            this.callApi();
            this.getLists(url,null,null,params,0,this.state.isAccount);
        });
        this.showModal();

        // reset selected data
        if (!isEmpty(keys)) {
            this.onBrowerChange(keys, selectedObj, true, false);
        } else {
            this.setState({rightDatas: []});
        }
    }
    handleOk() {
        const {rightDatas} = this.state;
        const {maxLength} = this.props;
        let values = [];
        let selectedData = {};
        if (!isEmpty(rightDatas)) {
            if (maxLength && maxLength < this.countCrm(rightDatas, true)) {
                window.alert(`所选人数不能超出${maxLength}人!`);
                return;
            }
            rightDatas.forEach((item)=> {
                let id;
                if (item.type === 'resource') {
                    id = item.id;
                } else {
                    if (!isEmpty(item.users)) {
                        id = [];
                        item.users.forEach((u)=> {
                            id.push(u.id);
                        })
                        id = id.join(',');
                    }
                }
                if (id) {
                    selectedData[id] = item;
                    values.push(id);
                }
            });
        }

        this.setState({
            visible: false,
            searchKeys: values,
            selectedData: selectedData
        });
        this.throwCurrentState(values.join(','), rightDatas);
        if (values.length > 0) WeaTools.callApi('/api/ec/api/hrm/newly', 'post', {ids: values.join(',')});
        this.setState(initialState);//初始化浏览框
        this.refs.browserRight && this.refs.browserRight.reset();
    }
    handleCancel() {
        this.setState(initialState);//初始化浏览框
        this.refs.browserRight && this.refs.browserRight.reset();
    }
    handleClear() {
        this.setState({
            visible: false,
            isClearData: !this.state.isClearData,
            rightDatas: [],
            rightCheckedKeys: [],
            leftTreeCheckedKeys: [],
            leftListSelectedKeys: [],
            leftListSelectedData: [],
            leftTreeCheckedData: [],
            leftGroupCheckedData: [],
            selectedData: {},
            searchKeys: [],
            leftGroupCheckedKeys: []
        });
        this.setState(initialState);//初始化浏览框
        this.throwCurrentState('', []);
        this.refs.browserRight && this.refs.browserRight.reset();
    }
    onBrowerChange(values, datas, needFormat = false, needOnchange = true) {
        let rDatas = [];
        values.forEach((v)=> {
            rDatas.push(datas[v]);
        })
        if (needFormat) {
            this.formatCheckedData(rDatas, true).then((result)=>{
                this.setState({searchKeys:values, selectedData: datas, rightDatas: result});
                if (needOnchange) this.throwCurrentState(values.join(','), result);
            })
        } else {
            this.setState({searchKeys:values, selectedData: datas, rightDatas: rDatas});
            if (needOnchange) this.throwCurrentState(values.join(','), rDatas);
        }
    }
    appendSearchValues(datas, needFilter = false) {
        const {searchKeys, selectedData, rightDatas} = this.state;
        let searchKeysB = cloneDeep(searchKeys);
        let selectedDataB = cloneDeep(selectedData);
        let rightDatasB = cloneDeep(rightDatas);
        if (needFilter) datas = this.filterDatas(datas);
        this.setSearchValues(datas, searchKeysB, selectedDataB, rightDatasB, true);
    }
    set(datas) {
        this.replaceSearchValues(datas);
    }
    replaceSearchValues(datas) {
        let searchKeysB = [];
        let selectedDataB = {};
        let rightDatasB = [];
        this.setSearchValues(datas, searchKeysB, selectedDataB, rightDatasB);
    }
    setSearchValues(datas, searchKeysB, selectedDataB, rightDatasB, doChange = false) {
        const {maxLength} = this.props;
        if (datas && datas.length > 0) {
            for (let i = 0; i< datas.length; i++) {
                let data = datas[i];
                let id;
                data.type = data.type || 'resource';
                data.lastname = data.lastname || data.name || '';

                if (data.type === 'all') {
                    // 所有人
                    data.nodeid = 'all_x';
                    id = data.ids;
                    searchKeysB = [id];
                    rightDatasB = [data];
                    selectedDataB = {};
                    selectedDataB[id] = data;
                    break;
                } else if (data.type === 'resource') {
                    data.nodeid = `resource_${data.id}x`;
                    id = data.id;
                    // // 去重
                    // const groups = datas.filter(d => d.type != 'resource');
                    // if (!isEmpty(groups)) {
                    //     groups.forEach((g) => {
                    //         if (g.users && g.users.filter((u) => u.id === data.id).length > 0) {
                    //             id = undefined;
                    //         }
                    //     })
                    // }
                } else {
                    data.nodeid = `${data.type}_${data.id}x`;
                    if (!isEmpty(data.users)) {
                        id = [];
                        data.users.forEach((u)=> {
                            id.push(u.id);
                        })
                        id = id.join(',');
                    }
                }
                if (id) {
                    searchKeysB.push(id);
                    rightDatasB.push(data);
                    selectedDataB[id] = data;
                }
            }

            if (maxLength && maxLength < this.countCrm(rightDatasB, true)) {
                window.alert(`所选人数不能超出${maxLength}人!`);
                return;
            }

        }
        this.setState({searchKeys: searchKeysB, selectedData: selectedDataB, rightDatas: rightDatasB});
        if (doChange) {
            this.throwCurrentState(searchKeysB.join(','), rightDatasB);
        }
        let ids = uniq(searchKeysB).join(',');
        this.setState({hiddenIds: ids});
    }
    // 获取到部门下的人员信息
    getCrms(params) {
        const {isAccount, checkStrictly} = this.state;
        let p = {};
        if (isAccount) p['isNoAccount'] = 1;
        if (!checkStrictly) p['alllevel'] = 1;
        return WeaTools.callApi(`/api/workflow/org/resource?types=${params}`, 'GET', p);
    }
    // 部分，分部的人员信息
    formatCheckedData(datas, callResource = false) {
        return new Promise((resolve, reject) => {
            let apiParams = [];
            this.resourcesCache = {};
            datas.forEach((item)=> {
                if (item.type !== 'resource') {
                    apiParams.push(item.type + '|' + item.id);
                }
                if (callResource && item.type === 'resource') {
                    apiParams.push(item.id);
                }
            })
            if (apiParams.length > 0) {
                this.getCrms(apiParams.join(',')).then((resp)=> {
                    if (resp) {
                        resp.forEach((r)=> {
                            this.resourcesCache[r.type + r.id] = r;
                        })
                    }
                    resolve(this.format(datas));
                }, ()=>{
                    window.alert('服务器搬到火星啦~')
                })
            } else {
                resolve(this.format(datas));
            }
        });
    }
    format(datas) {
        let result = [];
        const {isShowGroup} = this.props;
        datas.forEach((item)=> {
            let cache = this.resourcesCache[item.type + item.id] || item;
            if (item.type === 'resource') {
                result.push(cache);
            } else {
                item.users = cache.users;
                if (isShowGroup) {
                    if (item.isPrivate == 'true') {
                        result = result.concat(this.filterDatas(cache.users));
                    } else {
                        result.push(item);
                    }
                } else {
                    result = result.concat(this.filterDatas(cache.users));
                }
            }
        })
        return result;
    }
    onRightDoubleClick(key) {
        const {rightDatas} = this.state;
        const newRightDatas = rightDatas.filter(item => item.nodeid !== key);
        this.setState({rightDatas: newRightDatas, rightCheckedKeys: []});
    }
    onleftDoubleClick(datas) {
        const {rightDatas} = this.state;
        this.formatCheckedData(datas).then((datas)=>{
            this.setState({
                rightDatas: rightDatas.concat(datas),
                rightCheckedKeys:[],
                leftListSelectedData:[],
                leftTreeCheckedData:[],
                leftGroupCheckedData:[],
                leftGroupCheckedKeys:[],
                leftTreeCheckedKeys:[],
                leftListSelectedKeys:[]
            });
        })
    }
    moveTo = (direction) => {
        const {rightDatas, rightCheckedKeys, listDatas} = this.state;

        if (direction === 'right') {
            const {leftListSelectedData, leftTreeCheckedData, leftGroupCheckedData} = this.state;
            const datas = leftListSelectedData.concat(leftTreeCheckedData).concat(leftGroupCheckedData);
            this.formatCheckedData(datas).then((datas)=>{
                this.setState({
                    rightDatas: rightDatas.concat(datas),
                    rightCheckedKeys:[],
                    leftListSelectedData:[],
                    leftTreeCheckedData:[],
                    leftGroupCheckedData:[],
                    leftGroupCheckedKeys:[],
                    leftTreeCheckedKeys:[],
                    leftListSelectedKeys:[]
                });
            })
        }
        if (direction === 'left') {
            const newRightDatas = rightDatas.filter(item => !rightCheckedKeys.some(checkedKey => item.nodeid === checkedKey));

            this.setState({rightDatas: newRightDatas, rightCheckedKeys: []});
        }

        if (direction === 'allToLeft') {
            this.setState({rightDatas: [], rightCheckedKeys: []});
        }

        if (direction === 'allToRight') {
            if (this.leftListAllActive()) {
                this.setState({
                    rightDatas: rightDatas.concat(this.filterDatas(listDatas)),
                    rightCheckedKeys:[],
                    leftListSelectedData:[],
                    leftTreeCheckedData:[],
                    leftGroupCheckedData:[],
                    leftGroupCheckedKeys:[],
                    leftTreeCheckedKeys:[],
                    leftListSelectedKeys:[],
                })
            }
        }
    }
    filterDatas(datas) {
        const {rightDatas} = this.state;
        let res = [];
        let ids = [];
        if (rightDatas) {
            rightDatas.forEach((d) => {
                if (d.type == 'resource') {
                    ids.push(d.id)
                } else {
                    d.users && d.users.forEach((u)=> {
                        ids.push(u.id)
                    })
                }
            })
        }
        if (datas) {
           res = datas.filter((item) => ids.indexOf(item.id) == -1 || item.type != 'resource')
        }
        return res;
    }
    moveToLeft = () => this.moveTo('left')
    moveToRight = () => this.moveTo('right')
    moveAllToLeft = () => this.moveTo('allToLeft')
    moveAllToRight = () => this.moveTo('allToRight')

    countCrm(rightDatas, rNum = false) {
        let count = 0;
        let ids = [];
        rightDatas.forEach((item)=> {
            if (item.type === 'all') {
                count += item.count;
            } else if (item.type !== 'resource') {
                count += (item.users || []).length;
            } else {
                ids.push(item.id);
            }
        })
        count += uniq(ids).length;
        if (rNum) return count;
        return count > 0 ? `(${count})` : '';
    }
    leftListAllActive() {
        const {rightDatas, listDatas} = this.state;
        let bool = true;
        if (isEmpty(listDatas)) bool = false;
        if (!isEmpty(listDatas) && !isEmpty(rightDatas)) {
            let ids = [];
            rightDatas.forEach((d) => {
                if (d.type == 'resource') {
                    ids.push(d.id)
                } else {
                    d.users && d.users.forEach((u)=> {
                        ids.push(u.id)
                    })
                }
            })
            bool = listDatas.filter((l) => !ids.some(r => l.id === r)).length !== 0;
        }
        return bool;
    }
    strToArray(str) {
        let r = [];
        if (str) r.push(str);
        return r;
    }
    render() {
        const {fieldName,contentHeight=410,icon,dropMenuIcon,iconBgcolor,title,browerType,dataUrl,recentUrl,sameDepUrl,mySubUrl,min,max,virtualUrl,searchUrl}=this.props;
        const {id,name,style,topPrefix,topIconUrl,otherPara,dataKey,isMult,ifCheck,disabled,prefix,ifAsync,grouptree,resourcetree,value,type,mult,checkGroup} = this.props;
        const {companyId, loading, visible, showDrop,activeKey,showSearchAd,virtualDatas,grouptreeData,rsctreeData, listDatas, inputValue, pageSize, count, currentPage, hasPagination} = this.state;
        const {hiddenIds, searched,rightDatas, rightCheckedKeys,leftTreeCheckedKeys,leftListSelectedKeys,selectedData,searchKeys, leftGroupCheckedKeys, checkStrictly, isAccount, showAllbranch} = this.state;
        let titleEle = (
            <Row>
                <Col span="8" style={{paddingLeft:20,lineHeight:'48px'}}>
                    <div className="wea-hr-muti-input-title">
                        {iconBgcolor ?
                            <div className="wea-browser-single-icon-circle" style={{background: iconBgcolor}}>
                                <i className={icon}/>
                            </div>
                            : <span style={{verticalAlign:'middle',marginRight:10}}><i className={icon}/></span>
                        }
                        <span style={{verticalAlign:'middle'}}>{title}</span>
                    </div>
                </Col>
            </Row>
        );
        let menuItem = [];
        virtualDatas.map((item)=>{
            menuItem.push(<Menu.Item key={item.id}>{item.virtualtype}</Menu.Item>);
            menuItem.push(<Menu.Divider />)
        });
        const typeMenu = (
            <Menu className="wea-hr-muti-input-drop-menu"  onSelect={this.onSelect.bind(this)} selectedKeys={this.strToArray(companyId)}>{menuItem}</Menu>
        );
        let inputArr = (<WeaAssociativeSearchMult
                        {...this.props}
                        style={this.props.inputStyle}
                        datas={selectedData}
                        selectedValues={searchKeys}
                        isClearData={this.state.isClearData}
                        type={type}
                        clickCallback={this.onBrowerClick}
                        appendSearchValues={this.appendSearchValues.bind(this)}
                        onChange={this.onBrowerChange.bind(this)}
                        dropAllUserGroup={this.props.dropAllUserGroup}
                    />);
        const buttons = [
                <Button key="submit" type="primary" size="large" onClick={this.handleOk.bind(this) } disabled={this.countCrm(rightDatas, true) == 0}>确 定{this.countCrm(rightDatas)}</Button>,
                <Button key="clear" type="ghost" size="large" onClick={this.handleClear.bind(this)}>清 除</Button>,
                <Button key="back" type="ghost" size="large" onClick={this.handleCancel.bind(this)}>取 消</Button>];
        const searchsBox = this.getSearchs();
        const buttonsAd = this.getTabButtonsAd();
        const rightActive = leftTreeCheckedKeys.length + leftListSelectedKeys.length + leftGroupCheckedKeys.length > 0;
        const leftAllActive = (activeKey === '1' || activeKey === '2' || activeKey === '3' || searched) && this.leftListAllActive();
        const showList = activeKey === '1' || activeKey === '2' || activeKey === '3' || searched;
        let sheight = initHeight = contentHeight;
        if (hasPagination) sheight -= 35; //显示分页
        if (activeKey != "1" && activeKey != "5" && !searched) sheight -= 37; //显示维度
        return (
            <div>
               {inputArr}
               <input type="hidden" id={fieldName} name={fieldName} value={hiddenIds} />
               <Modal wrapClassName="wea-hr-muti-input wea-browser-modal"
                  title={titleEle}
                  // style={this.props.modalStyle}
                  zIndex={this.props.zIndex}
                  width={784}
                  maskClosable={false}
                  visible={visible}
                  onCancel={this.handleCancel.bind(this)}
                  footer={buttons}>
                    <Tabs
                        className="borderB"
                        onChange={this.onTabsChange.bind(this)}
                        activeKey={this.state.activeKey}>
                        <TabPane tab="最近" key="1"></TabPane>
                        <TabPane tab="同部门" key="2"></TabPane>
                        <TabPane tab="我的下属" key="3"></TabPane>
                        <TabPane tab="按组织结构" key="4"></TabPane>
                        <TabPane tab="常用组" key="5"></TabPane>
                    </Tabs>
                    <Spin spinning={loading}>
                        <div style={{padding: 10}}>
                            <div className='wea-hr-muti-input-left'>
                                <Row style={{height:"35px"}}>
                                    <Col span="18">
                                        <WeaInputSearch placeholder={this.props.is_012app ? "请输入人员姓名或工号" : "请输入人员姓名"} value={inputValue} onSearchChange={debounce(this.onSearchChange, 200).bind(this)} onSearch={this.onSearchChange.bind(this)}/>
                                    </Col>
                                    <Col span="6">
                                        <Button  className="wea-workflow-serch-condition" type="ghost" onClick={this.setShowSearchAd.bind(this,true)}>高级搜索</Button>
                                    </Col>
                                </Row>
                                <div className="wea-search-wrap"  style={{display:showSearchAd?'block':'none'}}>
                                    <Button type='ghost' className="wea-advanced-search" onClick={this.setShowSearchAd.bind(this,false)}>高级搜索</Button>
                                     <div className='wea-advanced-searchs' >
                                     <Form horizontal>
                                        {this.state.initialShowSearchAd && searchsBox}
                                         <div className="wea-search-buttons">
                                            <div style={{"textAlign":"center"}}>
                                            {this.state.initialShowSearchAd && buttonsAd && buttonsAd.map((data)=>{return (<span style={{marginLeft:15}}>{data}</span>)})}
                                            </div>
                                         </div>
                                        </Form>
                                     </div>
                                </div>
                                {activeKey != "1" && activeKey != "5" && !searched &&
                                <Row>
                                    <Col span={24}>
                                     <Dropdown overlay={typeMenu} trigger={['click']}>
                                        <a className="ant-dropdown-link" href="javascript:;">
                                          {dropMenuIcon}{this.state.companysDefault} <Icon type="down" style={{float:"right"}}/>
                                        </a>
                                      </Dropdown>
                                    </Col>
                                </Row>}
                                {
                                    activeKey != "1" &&
                                    <div className="operation-wrap" style={{top: (searched || activeKey == "5")? 42: 78}}>
                                        {
                                            activeKey == "3" &&
                                            <Button size="small" onClick={this.onBranchBtnClick.bind(this)} title={'显示下级下属'}>
                                                <span>
                                                    {showAllbranch?
                                                        <i className='icon-coms-DisplaySubordinates' style={{color: '#2db7f5'}}/>
                                                        :<i className='icon-coms-NoDisplayOfSubordinates'/>}</span>
                                            </Button>
                                        }
                                        {
                                            activeKey == "4" &&
                                            <Button size="small" onClick={() => this.setState({checkStrictly: !checkStrictly})} title={'包含下级机构'}>
                                                <span>
                                                    {!checkStrictly?
                                                        <i className='icon-coms-DisplaySubordinates' style={{color: '#2db7f5'}}/>
                                                        :<i className='icon-coms-NoDisplayOfSubordinates'/>}</span>
                                            </Button>
                                        }
                                        <Button size="small" onClick={this.onAccountBtnClick.bind(this)} title={isAccount?'隐藏无账号人员':'显示无账号人员'}>
                                            <span>{isAccount?
                                                <i className='icon-coms-ShowNoAccount' style={{color: '#2db7f5'}}/>
                                                :<i className='icon-coms-NoAccountNoDisplay'/>}</span>
                                        </Button>
                                    </div>
                                }
                                <WeaNewScroll height={sheight} ref="weaSrcoll">
                                    {showList &&
                                        <WeaHrmList
                                            {...this.props}
                                            onDoubleClick={this.onleftDoubleClick.bind(this)}
                                            onClick={this.onLeftListCheck.bind(this)}
                                            selectedKeys={leftListSelectedKeys}
                                            filterData={rightDatas}
                                            datas={listDatas}
                                        />
                                    }
                                    {!showList && activeKey == "4"
                                    && <WeaTreeHrMult dataUrl={resourcetree}
                                        checkStrictly={checkStrictly}
                                        isAccount={isAccount}
                                        virtualtype={this.state.companyId}
                                        className="rsc-wrapper"
                                        recentUrl={recentUrl}
                                        checkGroup={checkGroup} // 可以选择部门，分部
                                        treeKey="hr"
                                        topPrefix={topPrefix}
                                        id={id}
                                        isMult={true}
                                        checkedKeys={leftTreeCheckedKeys}
                                        onDoubleClick={this.onleftDoubleClick.bind(this)}
                                        checkedCb={this.onLeftTreeCheck.bind(this)}
                                        treeData={rsctreeData}
                                        filterData={rightDatas}
                                        defaultExpandedKeys={this.defaultExpandedKeys(rsctreeData.datas)}
                                    />}
                                    {!showList && activeKey == "5"
                                    && <WeaTreeHrMult dataUrl={grouptree}
                                        isAccount={isAccount}
                                        recentUrl={recentUrl}
                                        checkGroup={checkGroup}
                                        treeKey="hr"
                                        topPrefix={topPrefix}
                                        id={id}
                                        isMult={true}
                                        checkedKeys={leftGroupCheckedKeys}
                                        onDoubleClick={this.onleftDoubleClick.bind(this)}
                                        checkedCb={this.onLeftGroupCheck.bind(this)}
                                        treeData={grouptreeData}
                                        filterData={rightDatas}
                                        defaultExpandedKeys={this.defaultExpandedKeys(grouptreeData.datas)}
                                    />}
                                </WeaNewScroll>
                                {
                                    hasPagination &&
                                    <Pagination
                                        weaSimple
                                        showTotal={total => `共${total}条`}
                                        total={count}
                                        pageSize={pageSize}
                                        current={currentPage}
                                        onChange={this.onPageChange.bind(this)}/>
                                }

                            </div>
                            <div className='wea-transfer-opration'>
                                <Operation
                                  {...this.props}
                                  rightActive={rightActive}
                                  leftActive={rightCheckedKeys.length > 0}
                                  leftAllActive={leftAllActive}
                                  rightAllActive={rightDatas.length > 0}
                                  moveToRight={this.moveToRight}
                                  moveToLeft={this.moveToLeft}
                                  moveAllToRight={this.moveAllToRight}
                                  moveAllToLeft={this.moveAllToLeft}
                                />
                            </div>
                            <div className='wea-hr-muti-input-right'>
                                <WeaTransferRight
                                    {...this.props}
                                    ref="browserRight"
                                    data={rightDatas}
                                    checkedCb={this.onRightCheck.bind(this)}
                                    onDoubleClick={this.onRightDoubleClick.bind(this)}
                                    checkedKeys={rightCheckedKeys}
                                    height={initHeight}
                                    onDrag={(data) => {this.setState({rightDatas: data})}}
                                />
                            </div>
                        </div>
                    </Spin>
                </Modal>
            </div>
        )
    }
    onLeftListCheck (keys, datas) {
        const {leftListSelectedData} = this.state;
        let targets = leftListSelectedData.concat(datas);
        targets = uniqBy(targets, 'id');
        targets = targets.filter((t) => keys.indexOf(t.id) > -1);
        this.setState({
            leftListSelectedKeys: keys,
            leftListSelectedData: targets,
        })
    }
    onLeftTreeCheck (checkedKeys,datas) {
        this.setState({leftTreeCheckedKeys: checkedKeys, leftTreeCheckedData: datas});
    }
    onLeftGroupCheck (checkedKeys,datas) {
        this.setState({leftGroupCheckedKeys: checkedKeys, leftGroupCheckedData: datas});
    }
    onRightCheck (keys) {
        this.setState({rightCheckedKeys: keys});
    }
    throwCurrentState(ids, datas = []){
        // ids = uniq(ids.split(',')).join(',');
        this.setState({hiddenIds: ids});
        let names = [];
        datas.forEach(d => {
            d.name = d.name || d.lastname;
            names.push(d.name);
        })
        this.props.onChange && this.props.onChange(ids, names.join(','), datas);
    }

    getSearchs(){
        const {browserConditions} = this.state;
        let items = [];
        !isEmpty(browserConditions)&& browserConditions.forEach( field => {
            items.push({
                com:(<FormItem
                    label={`${field.label}`}
                    labelCol={{span: `${field.labelcol}`}}
                    wrapperCol={{span: `${field.fieldcol}`}}>
                        {WeaTools.getComponent(field.conditionType, field.browserConditionParam, field.domkey,this.props, field)}
                    </FormItem>),
                colSpan: 1,
                hide: WeaTools.isComponentHide(field),
            });
        });
        return <WeaSearchBrowserBox  items={items} />
    }

    getTabButtonsAd() {
        let _this = this;
        const {resetFields,validateFields} = this.props.form;
        return [
            <Button type="primary" onClick={(e)=>{this.goSearch(e)}}>搜索</Button>,
            <Button type="ghost" onClick={(e)=>{e.preventDefault(); this.reset();}}>重置</Button>,
            <Button type="ghost" onClick={()=>{_this.setState({showSearchAd:false})}}>取消</Button>
        ]
    }
    reset() {
        const {resetFields,setFieldsValue} = this.props.form;
        const {browserConditions} = this.state;
        const fields = {};
        browserConditions.forEach((c) => {
            let ct = c.conditionType.toUpperCase();
            let domkey = c.domkey[0];
            const filterKeys = [1, -1, '1', '-1'];
            if (ct === 'BROWSER') {
                if (!isEmpty(c.browserConditionParam) && filterKeys.indexOf(c.browserConditionParam.viewAttr) == -1) {
                    fields[domkey] = undefined;
                }
            } else {
                if (filterKeys.indexOf(c.viewAttr) == -1) {
                    fields[domkey] = undefined;
                }
            }
        })
        setFieldsValue(fields);
        this.setState({inputValue: ''});
    }
    defaultExpandedKeys(data){
        let arr = [];
        const {topPrefix} = this.props;
        const loop = data => data.forEach((item) => {
            if (item.children && !!item.open) {
                arr.push(`${topPrefix}0-${item.nodeid}`);
                loop(item.children);
            }else{
                !!item.open && arr.push(item.nodeid);
            }

        });
        !!data.open && arr.push(`${topPrefix}0-${data.nodeid}`);
        if(data.children){loop(data.children)}
        return arr;
    }
}
const formatSelectOptions = (options) => {
    let results = [];
    forEach(options, (option) => {
        results.push({
            value: option.id,
            name: option.name ? option.name : option.virtualtype
        })
    })
    return results;
}

export default Form.create()(main);